import { useRequest, useWatcher } from 'alova/client'
import {
  Button,
  Card,
  Col,
  Form,
  Input,
  InputProps,
  Row,
  Typography,
  DatePicker,
  Spin,
  Alert,
  App,
} from 'antd'
import React, { useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import dayjs from 'dayjs'
import '../styles/maintainAdd.css'
import TencentCOSUpload, {
  TencentCOSUploadRef,
} from '../components/TencentCOSUpload'
import { ContractViewVO, MaintainRecordInsertVO, MediaVO } from '../api/globals'

const { Item } = Form

const MaintainAdd: React.FC = () => {
  const [form] = Form.useForm<MaintainRecordInsertVO & ContractViewVO>()
  const navigate = useNavigate()
  const [contractCode, setContractCode] = React.useState<string>('')
  const fileRef = useRef<TencentCOSUploadRef | null>(null)
  const { message } = App.useApp()

  const { data, loading, error } = useWatcher(
    () =>
      Apis.cm.Wci({
        pathParams: {
          contractCode: contractCode,
        },
      }),
    [contractCode],
    {
      immediate: contractCode.length > 0, // Only trigger when contractCode has value
    }
  )

  const handleContractCodeBlur: InputProps['onBlur'] = (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    const value = e.target.value.trim()
    if (value) {
      setContractCode(value)
      form.setFieldsValue({ contractCode: value }) // Ensure form has the value
    }
  }

  React.useEffect(() => {
    if (data) {
      // Set form values when data is loaded
      form.setFieldsValue({
        houseCode: data.houseCode,
        name: data.name,
        contactName: data.contactName,
        contactMobile: data.contactMobile,
        address: data.address,
        productName: data.productName,
        productStartTime: data.productStartTime
          ? dayjs(data.productStartTime)
          : null,
        productEndTime: data.productEndTime ? dayjs(data.productEndTime) : null,
        lastMaintainTime: data.lastMaintainTime
          ? dayjs(data.lastMaintainTime)
          : null,
      })
    }
  }, [data, form])

  const { loading: submitLoading, send: submitMT } = useRequest(() =>
    Apis.mt.Add({
      data: form.getFieldsValue(),
    })
  )

  const handleSubmit = () => {
    form
      .validateFields()
      .then((values) => {
        const fileList = fileRef.current?.getUploadedFiles()
        if (fileList && fileList.length > 0) {
          values.file = fileList.map(
            (f): MediaVO => ({
              mediaName: f.name,
              mediaType: f.type,
              mediaPath: new URL(f.url!).pathname,
              url: f.url,
            })
          )
        }
        submitMT()
          .then((r) => {
            message.success('维保记录创建成功')
            navigate('/mt')
          })
          .catch((err) => {
            console.log('err', err)
            message.error('维保记录创建失败: ' + err.msg)
          })
      })
      .catch((error) => {
        console.log('err', error)
        const { errorFields } = error
        if (errorFields) {
          for (const field of errorFields) {
            const { errors } = field
            if (errors.length > 0) {
              const errorMessage = errors[0]
              message.error(errorMessage)
            }
          }
        }
      })
  }

  const renderContractInfo = () => {
    if (error) {
      return (
        <Col span={24}>
          <Alert
            message="获取合同信息失败"
            description={error.message}
            type="error"
            showIcon
          />
        </Col>
      )
    }

    if (loading) {
      return (
        <Col span={24} className="text-center">
          <Spin tip="正在加载合同信息..." />
        </Col>
      )
    }

    if (!data) {
      return (
        <Col span={24}>
          <Typography.Title level={3} className="!text-red-400">
            请先填写合同编号
            <br />
            获取必要信息
          </Typography.Title>
        </Col>
      )
    }

    return (
      <>
        <Col xs={24} sm={12} md={12} lg={12} xl={12}>
          <Item label="房屋编号" name="houseCode">
            <Input readOnly />
          </Item>
        </Col>
        <Col xs={24} sm={12} md={12} lg={12} xl={12}>
          <Item label="户主名称" name="name">
            <Input readOnly />
          </Item>
        </Col>
        <Col xs={24} sm={12} md={12} lg={128} xl={126}>
          <Item label="联系人" name="contactName">
            <Input readOnly />
          </Item>
        </Col>
        <Col xs={24} sm={12} md={128} lg={128} xl={126}>
          <Item label="联系电话" name="contactMobile">
            <Input readOnly />
          </Item>
        </Col>
        <Col span={24}>
          <Item label="小区住址" name="address">
            <Input readOnly />
          </Item>
        </Col>
        <Col xs={24} sm={12} md={12} lg={12} xl={12}>
          <Item label="产品名称" name="productName">
            <Input readOnly />
          </Item>
        </Col>
        <Col xs={24} sm={12} md={12} lg={12} xl={12}>
          <Item label="维保开始时间" name="productStartTime">
            <DatePicker style={{ width: '100%' }} disabled />
          </Item>
        </Col>
        <Col xs={24} sm={12} md={12} lg={12} xl={12}>
          <Item label="维保截止日期" name="productEndTime">
            <DatePicker style={{ width: '100%' }} disabled />
          </Item>
        </Col>
        <Col xs={24} sm={12} md={12} lg={12} xl={12}>
          <Item label="上次维保时间" name="lastMaintainTime">
            <DatePicker style={{ width: '100%' }} disabled />
          </Item>
        </Col>

        {/* Here you can add more form items for the maintenance order creation */}
        <Col span={24}>
          <Item
            label="维保过程"
            name="maintenanceContent"
            rules={[{ required: true }]}
          >
            <Input.TextArea rows={4} placeholder="请记录维保过程" />
          </Item>
        </Col>
        <Col span={24}>
          <Item
            label="维保结果"
            name="maintenanceResult"
            rules={[{ required: true }]}
          >
            <Input.TextArea rows={4} placeholder="请记录维保结果" />
          </Item>
        </Col>
        <Col span={24}>
          <Item label="维保记录附件：">
            <TencentCOSUpload ref={fileRef} />
          </Item>
        </Col>

        <Col span={24} className="text-right">
          <Button type="primary" loading={submitLoading} onClick={handleSubmit}>
            提交工单
          </Button>
        </Col>
      </>
    )
  }

  return (
    <div className="pl-8 pr-8 pt-8 pb-8 flex flex-col justify-start items-center ">
      <Card
        title="创建维保记录"
        extra={
          <Button type="primary" onClick={() => navigate('/mt')}>
            返回
          </Button>
        }
        className="max-w-7xl mx-auto min-md:!min-w-[1280px]"
      >
        <Form form={form} layout="horizontal" className="uniform-label-width">
          <Row gutter={[24, 16]}>
            <Col xs={24} sm={24} md={24} lg={24} xl={24}>
              <Item
                label="合同编号"
                name="contractCode"
                rules={[{ required: true, message: '请输入合同编号' }]}
              >
                <Input
                  className="!grow"
                  placeholder="请输入合同编号"
                  onBlur={handleContractCodeBlur}
                />
              </Item>
            </Col>
            {renderContractInfo()}
          </Row>
        </Form>
      </Card>
    </div>
  )
}

export default MaintainAdd
